<template>
	<view class="content">
		<cu-custom bgColor="bg-gradual-blue">
			<block slot="content">登录</block>
		</cu-custom>
		<view class="cu-form-group margin-top">
			<view class="title">账号：</view>
			<input placeholder="请输入账号" v-model="username" name="input"></input>
		</view>
		<view class="cu-form-group">
			<view class="title">密码：</view>
			<input placeholder="请输入密码" v-model="password" name="input"></input>
		</view>
		<view class="btn-row">
			<button class="cu-btn block bg-blue margin-tb-sm lg" @click="login">登录</button>
			<button class="cu-btn block bg-green margin-tb-sm lg" @click="register">注册账号</button>
		</view>
	</view>
</template>

<script>
	import Request from '../../lib/request.js'

	export default {
		data() {
			return {
				username: '',
				password: '',
			}
		},
		methods: {
			// 登录
			login() {
				if (this.username.length < 2) {
					uni.showToast({
						icon: 'none',
						title: '账号最短为 2 个字符'
					});
					return;
				}
				if (this.password.length < 6) {
					uni.showToast({
						icon: 'none',
						title: '密码最短为 6 个字符'
					});
					return;
				}

                let data = {
                    'username':this.username,
					'password':this.password
                };

                Request.httpRequest({url: 'User/userLogin',method: 'POST',}, data).then(res => {
					if(res.code == 1){
						//保存到本地缓存
						uni.setStorageSync('userInfo', res.data.userinfo)
						uni.setStorageSync('token', res.data.token)
						
						// 登录成功跳转首页
						uni.reLaunch({
							url:'../index/index'
						})
					}else{
						uni.showModal({
							content: res.msg,
							showCancel: false
						})
						console.log('登录失败', res.msg);
					}
                })
			},
			// 注册
			register(){
				uni.navigateTo({
					url:'/pages/register/register'
				})
			}
		},
	}
</script>

<style>
	.btn-row{
		position: fixed;
		display: flex;
		flex-direction: row;
		justify-content: space-between;
		bottom: 10px;
		width: 100%;
		padding: 0 2%;
	}
	.btn-row button{
		width: 49%;
	}
</style>
